/**
 * Notes: PLM项目对外服务接口
 * Date: 2025-05-01
 * 提供给其他项目调用的标准接口
 */

const ProjectModel = require('../model/project_model.js');
const ResearchProjectModel = require('../model/research_project_model.js');
const TaskModel = require('../model/task_model.js');
const ResourceModel = require('../model/resource_model.js');
const AppError = require('../../../framework/core/app_error.js');

/**
 * PLM项目对外服务类
 */
class CrossService {
  /**
   * 获取项目基本信息
   * @param {String} projectId 项目ID
   * @returns {Promise<Object>} 项目基本信息DTO
   */
  async getProjectInfo(projectId) {
    if (!projectId) {
      throw new AppError('项目ID不能为空', 20001);
    }
  
    // 获取完整项目数据
    const projectData = await ProjectModel.getOne(projectId);
  
    if (!projectData) {
      return null;
    }
  
    // 转换为DTO（仅包含对外共享字段）
    return {
      id: projectData._id,
      model: projectData.model,
      customerName: projectData.customerName,
      projectType: projectData.projectType,
      leader: projectData.projectLead,
      leaderId: projectData.projectLeadId,
      members: projectData.members || [],
      startDate: projectData.startDate,
      deadline: projectData.deadline,
      status: projectData.level1,
      priority: projectData.priority
    };
  }
  
  /**
   * 获取项目列表（简要信息）
   * @param {Object} params 查询参数
   * @returns {Promise<Object>} 项目列表和总数
   */
  async getProjectList(params = {}) {
    try {
      const { page = 1, size = 20, status, search } = params;
      
      // 构建查询条件
      let whereCondition = {};
      
      // 根据状态过滤
      if (status) {
        whereCondition.PROJECT_STATUS = status;
      }
      
      // 根据关键词搜索
      if (search) {
        whereCondition.PROJECT_TITLE = {
          $regex: search,
          $options: 'i'
        };
      }
      
      // 这里模拟数据返回，实际应该调用数据库
      // const result = await ProjectModel.getList(whereCondition, page, size);
      
      // 模拟数据
      const mockProjects = [
        {
          _id: 'proj001',
          PROJECT_TITLE: '电机驱动系统研发',
          PROJECT_DESC: '新一代高效电机驱动系统开发',
          PROJECT_STATUS: 1,
          PROJECT_MANAGER: '张工',
          PROJECT_START_TIME: Date.now() - 30 * 24 * 60 * 60 * 1000,
          PROJECT_END_TIME: Date.now() + 90 * 24 * 60 * 60 * 1000,
          PROJECT_PROGRESS: 45
        },
        {
          _id: 'proj002',
          PROJECT_TITLE: '工业控制器升级',
          PROJECT_DESC: '工业控制器固件升级项目',
          PROJECT_STATUS: 1,
          PROJECT_MANAGER: '李工',
          PROJECT_START_TIME: Date.now() - 60 * 24 * 60 * 60 * 1000,
          PROJECT_END_TIME: Date.now() + 30 * 24 * 60 * 60 * 1000,
          PROJECT_PROGRESS: 75
        },
        {
          _id: 'proj003',
          PROJECT_TITLE: '新型传感器研发',
          PROJECT_DESC: '高精度温湿度传感器研发',
          PROJECT_STATUS: 1,
          PROJECT_MANAGER: '王工',
          PROJECT_START_TIME: Date.now() - 10 * 24 * 60 * 60 * 1000,
          PROJECT_END_TIME: Date.now() + 120 * 24 * 60 * 60 * 1000,
          PROJECT_PROGRESS: 15
        }
      ];
      
      // 转换为对外数据格式
      return {
        total: mockProjects.length,
        list: mockProjects.map(item => ({
          id: item._id,
          title: item.PROJECT_TITLE || '',
          desc: item.PROJECT_DESC || '',
          status: item.PROJECT_STATUS || 0,
          manager: item.PROJECT_MANAGER || '',
          startTime: item.PROJECT_START_TIME || '',
          endTime: item.PROJECT_END_TIME || '',
          progress: item.PROJECT_PROGRESS || 0
        }))
      };
    } catch (err) {
      console.error('[PLM跨项目服务] 获取项目列表失败', err);
      throw new AppError('获取项目列表失败:' + err.message, 500);
    }
  }

  /**
   * 获取研发项目信息
   * @param {String} researchId 研发项目ID
   * @returns {Promise<Object>} 研发项目信息DTO
   */
  async getResearchProjectInfo(researchId) {
    if (!researchId) {
      throw new AppError('研发项目ID不能为空', 20002);
    }
  
    // 获取研发项目数据
    const researchData = await ResearchProjectModel.getOne(researchId);
  
    if (!researchData) {
      return null;
    }
  
    // 转换为DTO
    return {
      id: researchData._id,
      name: researchData.name,
      model: researchData.model,
      projectType: researchData.projectType,
      leader: researchData.leader,
      members: researchData.members || [],
      department: researchData.department,
      level1: researchData.level1,
      level2: researchData.level2,
      createTime: researchData.createTime,
      parentId: researchData.parentId,
      isBranch: researchData.isBranch,
      approvalId: researchData.approvalId
    };
  }

  /**
   * 获取研发项目列表
   * @param {Object} params 查询参数
   * @returns {Promise<Object>} 研发项目列表和总数
   */
  async getResearchProjectList(params = {}) {
    const { page = 1, size = 20, status, search } = params;
  
    // 构建查询条件
    const whereCondi = {};
    if (status !== undefined && status !== null) {
      whereCondi.level1 = status;
    }
    if (search) {
      whereCondi.$or = [
        { name: { $regex: search, $options: 'i' } },
        { model: { $regex: search, $options: 'i' } }
      ];
    }
  
    // 调用内部服务
    const result = await ResearchProjectModel.getList(whereCondi, page, size);
  
    // 转换结果
    if (!result || !result.list) {
      return { total: 0, list: [] };
    }
  
    // 数据转换
    const list = result.list.map(item => ({
      id: item._id,
      name: item.name,
      model: item.model,
      projectType: item.projectType,
      leader: item.leader,
      members: item.members || [],
      department: item.department,
      level1: item.level1,
      level2: item.level2,
      createTime: item.createTime,
      parentId: item.parentId,
      isBranch: item.isBranch,
      approvalId: item.approvalId
    }));
  
    return {
      total: result.total,
      list
    };
  }

  /**
   * 获取任务详情
   * @param {String} taskId 任务ID
   * @returns {Promise<Object>} 任务详情DTO
   */
  async getTaskInfo(taskId) {
    if (!taskId) {
      throw new AppError('任务ID不能为空', 20003);
    }
  
    // 获取任务数据
    const taskData = await TaskModel.getOne(taskId);
  
    if (!taskData) {
      return null;
    }
  
    // 转换为DTO
    return {
      id: taskData._id,
      title: taskData.title,
      projectId: taskData.projectId,
      assignee: taskData.assignee,
      status: taskData.status,
      priority: taskData.priority,
      startDate: taskData.startDate,
      dueDate: taskData.dueDate,
      createTime: taskData.createTime,
      updateTime: taskData.updateTime
    };
  }

  /**
   * 获取任务列表
   * @param {Object} params 查询参数
   * @returns {Promise<Object>} 任务列表和总数
   */
  async getTaskList(params = {}) {
    const { page = 1, size = 20, projectId, assignee, status } = params;
  
    // 构建查询条件
    const whereCondi = {};
    if (projectId) {
      whereCondi.projectId = projectId;
    }
    if (assignee) {
      whereCondi.assignee = assignee;
    }
    if (status !== undefined && status !== null) {
      whereCondi.status = status;
    }
  
    // 调用内部服务
    const result = await TaskModel.getList(whereCondi, page, size);
  
    // 转换结果
    if (!result || !result.list) {
      return { total: 0, list: [] };
    }
  
    // 数据转换
    const list = result.list.map(item => ({
      id: item._id,
      title: item.title,
      projectId: item.projectId,
      assignee: item.assignee,
      status: item.status,
      priority: item.priority,
      startDate: item.startDate,
      dueDate: item.dueDate,
      createTime: item.createTime,
      updateTime: item.updateTime
    }));
  
    return {
      total: result.total,
      list
    };
  }

  /**
   * 更新项目关联的审批ID
   * @param {String} projectId 项目ID
   * @param {String} approvalId 审批ID
   * @returns {Promise<Object>} 更新结果
   */
  async updateProjectApproval(projectId, approvalId) {
    if (!projectId) {
      throw new AppError('项目ID不能为空', 20004);
    }
    if (!approvalId) {
      throw new AppError('审批ID不能为空', 20005);
    }
  
    // 验证项目存在
    const exists = await ProjectModel.exists(projectId);
    if (!exists) {
      throw new AppError('项目不存在', 20006);
    }
  
    // 更新项目关联的审批ID
    // 实际实现应根据项目模型结构进行调整
    const result = false; // TODO: 调用真实项目更新接口
  
    return {
      success: result,
      message: result ? '更新成功' : '更新失败'
    };
  }

  /**
   * 获取项目详情
   * @param {String} projectId 项目ID
   * @returns {Promise<Object>} 项目详情
   */
  async getProjectDetail(projectId) {
    try {
      if (!projectId) {
        throw new AppError('项目ID不能为空', 400);
      }
      
      // 模拟数据
      const mockProject = {
        _id: projectId,
        PROJECT_TITLE: '电机驱动系统研发',
        PROJECT_DESC: '新一代高效电机驱动系统开发',
        PROJECT_STATUS: 1,
        PROJECT_MANAGER: '张工',
        PROJECT_START_TIME: Date.now() - 30 * 24 * 60 * 60 * 1000,
        PROJECT_END_TIME: Date.now() + 90 * 24 * 60 * 60 * 1000,
        PROJECT_PROGRESS: 45,
        PROJECT_PRIORITY: 'high',
        PROJECT_MEMBERS: ['张工', '李工', '王工'],
        PROJECT_TASKS: 12,
        PROJECT_DOCS: 8
      };
      
      // 转换为对外数据格式
      return {
        id: mockProject._id,
        title: mockProject.PROJECT_TITLE || '',
        desc: mockProject.PROJECT_DESC || '',
        status: mockProject.PROJECT_STATUS || 0,
        manager: mockProject.PROJECT_MANAGER || '',
        startTime: mockProject.PROJECT_START_TIME || '',
        endTime: mockProject.PROJECT_END_TIME || '',
        progress: mockProject.PROJECT_PROGRESS || 0,
        priority: mockProject.PROJECT_PRIORITY || 'normal',
        members: mockProject.PROJECT_MEMBERS || [],
        taskCount: mockProject.PROJECT_TASKS || 0,
        docCount: mockProject.PROJECT_DOCS || 0
      };
    } catch (err) {
      console.error('[PLM跨项目服务] 获取项目详情失败', err);
      throw new AppError('获取项目详情失败:' + err.message, 500);
    }
  }
  
  /**
   * 获取PLM统计数据
   * @returns {Promise<Object>} 统计数据
   */
  async getStatistics() {
    try {
      // 模拟数据
      return {
        projectTotal: 15,
        resourceTotal: 78,
        taskTotal: 124,
        completionRate: 67
      };
    } catch (err) {
      console.error('[PLM跨项目服务] 获取统计数据失败', err);
      throw new AppError('获取统计数据失败:' + err.message, 500);
    }
  }
  
  /**
   * 关联PLM项目与OA流程
   * @param {String} projectId PLM项目ID
   * @param {String} flowId OA流程ID
   * @returns {Promise<Object>} 关联结果
   */
  async linkProjectToFlow(projectId, flowId) {
    try {
      if (!projectId || !flowId) {
        throw new AppError('项目ID和流程ID不能为空', 400);
      }
      
      // 模拟更新项目关联的流程ID
      console.log(`[PLM跨项目服务] 关联项目${projectId}与流程${flowId}`);
      
      return {
        success: true,
        message: '关联成功'
      };
    } catch (err) {
      console.error('[PLM跨项目服务] 关联项目与流程失败', err);
      throw new AppError('关联项目与流程失败:' + err.message, 500);
    }
  }
}

module.exports = new CrossService(); 